import React from 'react';
import {connect} from 'react-redux'
import {BackHandler , Alert} from 'react-native';
import AppNavigator from './appNavigator'
import { addNavigationHelpers,NavigationActions } from 'react-navigation';

class App extends React.Component {

    componentDidMount() {
      BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
    }
    componentWillUnmount() {
      BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
    }
    onBackPress = () => {
      const { dispatch, nav } = this.props;
      if (nav.index === 0) {
        return false;
      }
      const route = nav.routes[nav.routes.length-1];
      if (route.routeName == "Cpgl" || route.routeName == "Program" ){
          Alert.alert('提示',
          "是否返回",
          [
              {text: '否', onPress: () => {}},
              {text: '是', onPress: () => { dispatch(NavigationActions.back());}},
          ]);
          return true;
      } else if (route.routeName == 'Main'){
        Alert.alert('提示',
          "确认是否退出",
          [
              {text: '取消', onPress: () => {}},
              {text: '退出', onPress: () => { BackHandler.exitApp(); } },
          ]);
          return true;

      } else{
          dispatch(NavigationActions.back());
          return true;
      }
    };

    render() {
      return (
        <AppNavigator navigation={addNavigationHelpers({
          dispatch: this.props.dispatch,
          state: this.props.nav,
        })} />
      );
    }
  }
  
  const mapStateToProps = (state) => ({
    nav: state.nav
  });
  
  const AppWithNavigationState = connect(mapStateToProps)(App);

  export default AppWithNavigationState;